<?php

namespace App\Http\Controllers\Admin\Dispatch;

use App\Exports\CarExport;
use App\Exports\MaterialExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\dispatch\CarRequest;
use App\Imports\CarImport;
use App\Imports\MaterialImport;
use App\Models\dispatch\CarModel;
use App\Models\dispatch\DriverModel;
use App\Models\dispatch\MaterialModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class Car extends Controller
{
    use CarRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $car_number = $request->input('car_number', '');
        $type_id = $request->input('type_id', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');

        $query = CarModel::query()->with(['create_admin', 'agent', 'type']);

        if($car_number){
            $query = $query->where('car_number', $car_number);
        }

        if($type_id){
            $query = $query->where('type_id', $type_id);
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'type_id' => $item->type_id,
                'type_name' => $item->type ? $item->type->name : '',
                'agent_id' => $item->agent_id,
                'agent_name' => $item->agent ? $item->agent->name : '',
                'car_number' => $item->car_number,
                'volume' => $item->volume,
                'weight' => $item->weight,
                'driver_id' => $item->driver_id,
                'hk_driver_id' => $item->hk_driver_id,
                'driver_info' => '',
                'hk_driver_info' => '',
                'created_at' => $item->created_at->toDateTimeString(),
                'create_user' => $item->create_admin ? $item->create_admin->staff->name: '',
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    /**
     * Notes:添加
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = new CarModel();
        $model->car_number = $params['car_number'];
        $model->type_id = $params['type_id'];
        $model->agent_id = $params['agent_id'];
        $model->weight = $params['weight'];
        $model->volume = $params['volume'];
        $model->driver_id = $params['driver_id'] ?? 0;
        $model->hk_driver_id = $params['hk_driver_id'] ?? 0;
        $model->created_admin_id = $auth->id;
        $model->save();

        return $this->success();
    }

    public function update(Request $request, $id){
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = CarModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }


        $model->car_number = $params['car_number'];
        $model->type_id = $params['type_id'];
        $model->agent_id = $params['agent_id'];
        $model->weight = $params['weight'];
        $model->volume = $params['volume'];
        $model->driver_id = $params['driver_id'] ?? 0;
        $model->hk_driver_id = $params['hk_driver_id'] ?? 0;

        $model->save();

        return $this->success();
    }


    public function delete(int $id){
        $model = CarModel::find($id);
        if(!$model) {
            return $this->error('记录不存在');
        }
        $model->delete();
        return $this->success();
    }

    //配载任务司机选择
    public function select(Request $request)
    {
        $type_id = $request->input('type_id', '');

        $cars = CarModel::where('type_id', $type_id)->get();

        $list = $cars->map(function($item) {
//            $car_number = $item->car_number;
//
//            $driver_name = $item->driver ? $item->driver->name : '';
//            $hk_driver_name = $item->hk_driver ? $item->hk_driver->name : '';
//
//            $value = $car_number . '（';
//            if($driver_name){
//                $value .= '大陆司机：'.$driver_name;
//            }
//
//            if($hk_driver_name){
//                $value .= ' + 香港司机：'.$hk_driver_name;
//            }
//            $value .= ')';
//
//            $res = [
//                'id' => $item->id,
//                'value' => $value,
//            ];
            $res = [
                'id' => $item->id,
                'value' => $item->car_number,
            ];

            return $res;
        });

        return $this->success($list);

    }


    public function export(Request $request)
    {
        $ids = $request->input('ids', []);
        if(empty($ids)){
            return $this->error('请选择要导出的数据');
        }

        $query = CarModel::query()->with(['agent', 'driver', 'hk_driver', 'type']);
        $query->whereIn('id', $ids);
        $items = $query
            ->orderBy('id', 'desc')
            ->get();


        $list = $items->map(function($item) {
            $res = [
                'agent_name' => $item->agent ? $item->agent->name : '',
                'type_name' => $item->type ? $item->type->name : '',
                'car_number' => $item->car_number,
                'driver_name' => $item->driver->name ?? '',
                'hk_driver_name' => $item->hk_driver->name ?? '',
                'volume' => $item->volume,
                'weight' => $item->weight,
            ];
            return $res;
        });

        $file_name = '车辆列表-'.date('Ymd').'.xlsx';
        return Excel::download(new CarExport($list), $file_name);
    }

    public function import(Request $request)
    {
        $auth = $request->get('auth');
        $file = $request->file('file');
        if(!$file){
            return $this->error('请选择文件');
        }

        $import = new CarImport();
        Excel::import($import, $file);


        $res = $import->get_result();

        if(isset($res->error) && $res->error){
            return $this->error(implode(',', $res->error));
        }

        $lines = $res->lines;

        DB::beginTransaction();
        try {
            foreach ($lines as $line){

                $model = new CarModel();
                $model->car_number = $line['car_number'];
                $model->type_id = $line['type_id'];
                $model->agent_id = $line['agent_id'];
                $model->weight = $line['weight'];
                $model->volume = $line['volume'];
                $model->driver_id = $line['driver_id'];
                $model->hk_driver_id = $line['hk_driver_id'];
                $model->created_admin_id = $auth->id;
                $model->save();

            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return  $this->success();
    }

}
